package com.itxiaoxiong.chat.socket;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;

@Component
public class ProxyServerManager {

    private final HashMap<String, ProxyServer> proxyServers = new HashMap<>();

    public ProxyServer getOrCreateProxyServer(String userId, HashMap<String, BlockingQueue<String>> userQueues) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(userId);
        if (rootNode.has("userId")) {
            userId = rootNode.get("userId").asText();
        }
        ProxyServer server = proxyServers.get(userId);
        if (server == null) {
            System.out.println("创建一个新的proxyServer" + userId);
            server = new ProxyServer("localhost", 6789, userId,userQueues);
            proxyServers.put(userId, server);
        } else {
            System.out.println("现有的ProxyServer对象 " + userId);
        }
        return server;
    }

    public void disconnectProxyServer(String userId) throws IOException {
        if(proxyServers.containsKey(userId)){
        ProxyServer server = proxyServers.remove(userId);
        if (server!= null) {
            server.close();
            System.out.println("成功断开用户 " + userId + " 与代理服务器的连接");
        } else {
            System.out.println("未找到用户 " + userId + " 的代理服务器连接");
        }}else{
            System.out.println("未找到用户 " + userId + " 的代理服务器连接");
        }
    }

    public boolean containsUserId(String userId) {
        return proxyServers.containsKey(userId);
    }
}

